<template>
    <view class="goods-details">
        <!-- 顶部导航 -->
        <u-navbar
            id="navbar"
            :border-bottom="false"
            :background="{
                background: 'rgba(256,256,256, ' + navStyle.backgroundBg + ')'
            }"
            :back-bg="'rgba(0,0,0,' + navStyle.backBg + ')'"
            :back-icon-color="navStyle.backColor"
            :immersive="true"
        >
            <view style="width: 100%" :style="{ opacity: navStyle.backgroundBg }">
                <tabs
                    sticky-bg-color="transparent"
                    v-if="navStyle.backgroundBg > 0.1"
                    :show-bar="true"
                    :bar-width="60"
                    :is-scroll="false"
                    :current="active"
                    bg-color="transparent"
                    :style="{ width: '100%', opacity: navStyle.backgroundBg }"
                    @change="changeActive"
                    :config="{ activeColor: '#24A3FF', underLineColor: '#24A3FF' }"
                >
                    <tab title="商品"></tab>
                    <tab title="评价"></tab>
                    <tab title="详情"></tab>
                </tabs>
            </view>
        </u-navbar>

        <!-- #ifdef H5 -->
        <download-nav v-if="showDownload"></download-nav>
        <!-- #endif -->
        <loading-view v-if="isFirstLoading"></loading-view>

        <view class="contain" v-if="!isNull" id="goods">
            <bubble-tips :top="90 + navHeight + 'rpx'" />
            <product-swiper :imgUrls="swiperList" :video="goodsDetail.video" />

            <view class="goods-info bg-white">
                <view class="info-header row" v-if="goodsType != 1">
                    <view class="price row flex1">
                        <view class="primary mr10">
                            <price-format
                                color="#FF2C3C"
                                :first-size="46"
                                :second-size="32"
                                :subscript-size="32"
                                :price="checkedGoods.price || goodsDetail.price"
                                :weight="500"
                            ></price-format>
                        </view>
                        <view class="line-through muted md">
                            <price-format
                                :price="checkedGoods.market_price || goodsDetail.market_price"
                            ></price-format>
                        </view>
                    </view>
                    <image
                        class="icon-share"
                        src="/static/images/icon_share.png"
                        @tap="showShareBtn = true"
                    ></image>
                </view>
                <view
                    class="row"
                    v-if="!goodsType && (checkedGoods.member_price || goodsDetail.member_price)"
                >
                    <view class="vip-price row">
                        <view class="price-name xxs">会员价</view>
                        <view style="padding: 0 11rpx">
                            <price-format
                                :price="checkedGoods.member_price || goodsDetail.member_price"
                                :first-size="26"
                                :second-size="26"
                                :subscript-size="22"
                                :weight="500"
                                color="#7B3200"
                            ></price-format>
                        </view>
                    </view>
                </view>
                <view class="row">
                    <view class="name lg bold">{{ goodsDetail.name }}</view>
                    <image
                        class="icon-share"
                        src="/static/images/icon_share.png"
                        @tap="showShareBtn = true"
                        v-if="goodsType == 1"
                    ></image>
                </view>
                <view class="row-between xs lighter" style="padding: 0 24rpx 20rpx">
                    <text v-if="goodsDetail.stock !== true"
                        >库存: {{ checkedGoods.stock || goodsDetail.stock }}件</text
                    >
                    <text>销量: {{ goodsDetail.sales_sum }}件</text>
                    <text>浏览量: {{ goodsDetail.click_count }}次</text>
                </view>
            </view>

            <view
                v-if="!goodsType"
                class="spec row bg-white mt20 ml20 mr20 br20"
                @tap="showSpecFun(0)"
            >
                <view class="text lighter">已选</view>
                <view class="line1 mr20" style="flex: 1">{{
                    checkedGoods.spec_value_str || '默认'
                }}</view>
                <image class="icon-sm" src="/static/images/arrow_right.png"></image>
            </view>

            <view class="evaluation bg-white mt20 mr20 ml20 br20" id="evaluation">
                <navigator
                    hover-class="none"
                    :url="'/pages/all_comments/all_comments?id=' + goodsDetail.id"
                    class="title row-between"
                >
                    <view>
                        <text class="balck md mr10">商品评价</text>
                        <!-- <text class="ornament sm">好评率{{ comment.goods_rate || '0%' }}</text> -->
                    </view>
                    <view class="row">
                        <text class="lighter">查看全部</text>
                        <image class="icon-sm" src="/static/images/arrow_right.png"></image>
                    </view>
                </navigator>
                <view class="con" v-if="comment.goods_rate">
                    <view class="user-info row">
                        <image class="avatar mr20" :src="comment.avatar"></image>
                        <view class="user-name md mr10">{{ comment.nickname }}</view>
                    </view>
                    <view class="muted xs mt10">
                        <text class="mr20">{{ comment.create_time }}</text>
                    </view>
                    <view v-if="comment.comment" class="dec mt20">{{ comment.comment }}</view>
                </view>
                <view class="con row-center muted" v-else>暂无评价</view>
            </view>

            <!-- 猜你喜欢 -->
            <template v-if="goodsLike.length">
                <view class="goods-like mt20 bg-white mr20 ml20 br20">
                    <goods-like :list="goodsLike" />
                </view>
            </template>

            <!-- 详情 -->
            <view class="details mt20 bg-white mr20 ml20 br20" id="details">
                <u-tabs
                    :list="getTabList(1)"
                    :is-scroll="false"
                    :current="currentTab"
                    :bold="true"
                    font-size="30rpx"
                    active-color="#24A3FF"
                    inactive-color="#333333"
                    bar-width="120"
                    bar-height="6"
                    @change="changeTab"
                />

                <view class="content">
                    <template v-if="currentTab === 0">
                        <u-parse
                            :html="goodsDetail.content"
                            :lazy-load="true"
                            :show-with-animation="true"
                        ></u-parse>
                    </template>
                    <template v-else-if="currentTab === 1">
                        <!-- <view>租赁说明。。。。</view> -->
                    </template>
                </view>
            </view>

            <view class="footer row bg-white fixed">
                <navigator class="btn column-center" hover-class="none" url="/pages/index/index">
                    <image class="icon-md" src="/static/images/icon_home.png"></image>
                    <text class="xxs lighter">首页</text>
                </navigator>
                <view class="btn column-center" @tap="collectGoodsFun">
                    <image
                        class="icon-md"
                        :src="
                            goodsDetail.is_collect == 1
                                ? '/static/images/icon_collection_s.png'
                                : '/static/images/icon_collection.png'
                        "
                    ></image>
                    <text class="xxs lighter">收藏</text>
                </view>
                <navigator
                    class="btn cart column-center"
                    hover-class="none"
                    open-type="navigate"
                    url="/pages/shop_cart/shop_cart"
                >
                    <image class="icon-md" src="/static/images/icon_cart.png"></image>
                    <text class="xxs lighter">购物车</text>
                    <u-badge
                        v-if="cartNum"
                        bgColor="#FF2C3C"
                        fontSize="20"
                        :offset="[8, 10]"
                        :count="cartNum"
                    />
                </navigator>
                <view
                    v-if="btnText.yellow"
                    class="add-cart br60 primary mr10 md ml20"
                    @tap="showSpecFun(1)"
                    >{{ btnText.yellow }}</view
                >
                <view class="right-buy br60 white mr20 ml10 md" @tap="showSpecFun(2)">{{
                    btnText.red
                }}</view>
            </view>
        </view>
        <view v-else>
            <view class="details-null column-center">
                <image class="img-null" src="/static/images/goods_null.png"></image>
                <view class="xs muted">该商品已下架或不存在，去逛逛别的吧~</view>
            </view>
            <recommend></recommend>
        </view>

        <!-- 商品规格选择 -->
        <spec-popup
            :show="showSpec"
            :goods="goodsDetail"
            :is-seckill="goodsType == 1"
            @close="showSpec = false"
            :show-add="popupType == 1 || popupType == 0"
            :show-buy="popupType == 2 || popupType == 0"
            :showConfirm="popupType == 3"
            @buynow="onBuy"
            @addcart="onAddCart"
            @change="onChangeGoods"
            :group="Boolean(isGroup)"
            :red-btn-text="btnText.red"
            :yellow-btn-text="btnText.yellow"
            @confirm="onConfirm"
        ></spec-popup>

        <!-- 分享 -->
        <!-- <share-popup 
		  :show="showShareBtn" 
		  :goods-id="id"  
		  type="goods"
		  :img-url="goodsDetail.image" 
		  :summary="goodsDetail.remark" 
		  :share-title="goodsDetail.name" 
		  @close="showShareBtn = false" 
		/> -->

        <share-popup
            :show="showShareBtn"
            @close="showShareBtn = false"
            :share-id="id"
            pagePath="pages/goods_details/goods_details"
            :type="1"
            :config="{
                avatar: userInfo.avatar,
                nickname: userInfo.nickname,
                image: goodsDetail.image,
                price: goodsDetail.price,
                marketPrice: goodsDetail.market_price,
                name: goodsDetail.name
            }"
        >
        </share-popup>

        <!-- <float-tab></float-tab> -->
    </view>
</template>

<script>
import { getGoodsDetail, addCart, getPoster, getCartNum } from '@/api/store'
import { collectGoods } from '@/api/user'
import { getGoodsCoupon, teamCheck } from '@/api/activity'
import { mapActions, mapGetters } from 'vuex'
import { arraySlice } from '@/utils/tools'
import { toLogin } from '@/utils/login'
import { getUser, inputInviteCode } from '@/api/user'
import Cache from '@/utils/cache'
import { strToParams, getRect } from '@/utils/tools'
const app = getApp()
export default {
    data() {
        return {
            isFirstLoading: true,
            isNull: false,
            showSpec: false,
            showShareBtn: false,
            popupType: '',
            swiperList: [],
            goodsDetail: {},
            goodsLike: [],
            goodsType: 0,
            checkedGoods: {},
            comment: {},
            countTime: 0,
            tagStyle: {
                img: 'width:100%;'
            },
            isGroup: 0,
            id: '',
            showDownload: false,

            currentTab: 0, // Tabs当前位置
            // Tabs 列表
            tabsList: [
                {
                    kay: 'goods',
                    name: '商品详情'
                },
                {
                    key: 'lease',
                    name: '租赁说明'
                }
            ],

            navStyle: {
                backBg: 0.4,
                backgroundBg: 0,
                backColor: 'rgba(256,256,256,1)'
            },
            active: 0,
            topArr: [],
            isTouchStart: false
        }
    },
    onLoad(options) {
        if (options && options.scene) {
            let scene = strToParams(decodeURIComponent(options.scene))
            console.log(scene, decodeURIComponent(options.scene))
            options.id = scene.id
        }
        // #ifdef H5
        if (options && options.isapp == 1) {
            this.showDownload = true
        }
        // #endif
        if (!options.id) {
            return this.$toast(
                {
                    title: '缺少参数，无法查看商品'
                },
                {
                    tab: 3
                }
            )
        } else {
            this.id = options.id
        }
        if (!this.isLogin) return
        this.getCartNum()

        console.log(uni.$u.config.v)
    },
    onShow() {
        this.getGoodsDetailFun()
    },

    onPageScroll(e) {
        const top = uni.upx2px(500)
        const { scrollTop } = e
        const percent = scrollTop / top
        this.navStyle.backgroundBg = percent
        this.navStyle.backBg = 0.4 * (0.5 - percent)
        this.navStyle.backColor =
            percent < 0.5
                ? 'rgba(256,256,256,' + (0.5 - percent) * 2 + ')'
                : 'rgba(0,0,0,' + (percent - 0.5) * 2 + ')'
        if (!this.isTouchStart) return
        const topList = this.topArr
            .map((item, index) => ({
                index,
                top: item
            }))
            .filter((item) => item.top <= scrollTop)

        if (topList.length) {
            const index = topList.sort((a, b) => b.top - a.top)[0].index
            if (this.active == index) return
            this.active = index
        }
    },

    methods: {
        ...mapActions(['getCartNum']),

        changeActive(index) {
            this.isTouchStart = false

            uni.pageScrollTo({
                scrollTop: this.topArr[index],
                duration: 200
            })
        },

        getRectInfo() {
            if (this.topArr.length) return
            getRect('#goods').then((res) => {
                this.topArr[0] = res.top - this.navHeight
            })
            getRect('#evaluation').then((res) => {
                this.topArr[1] = res.top - this.navHeight
            })
            getRect('#details').then((res) => {
                this.topArr[2] = res.top - this.navHeight
            })
        },

        // 改变当前的Tabs位置
        changeTab(index) {
            this.currentTab = index
        },

        // 获Tabs列表
        getTabList(count) {
            const list = this.tabsList
            list.length = count
            return list
        },

        async getGoodsDetailFun() {
            const { data, code } = await getGoodsDetail({
                id: this.id
            })
            if (code == 1) {
                let { goods_image, content, comment, like, activity } = data

                this.goodsDetail = data
                this.swiperList = goods_image
                this.comment = comment
                this.goodsLike = like

                this.$nextTick(() => {
                    this.isFirstLoading = false

                    // 滚动到顶部，防止h5端出现问题
                    uni.pageScrollTo({
                        scrollTop: 0,
                        duration: 0
                    })
                    this.getRectInfo()
                })
                // #ifdef H5
                let options = {
                    shareTitle: data.name,
                    shareLink: location.href + '&invite_code=' + this.userInfo.distribution_code,
                    shareImage: data.image,
                    shareDesc: data.remark
                }
                this.wxShare(options)
                // #endif
            } else {
                this.isNull = true
                this.isFirstLoading = false
            }
        },
        async collectGoodsFun() {
            if (!this.isLogin) return toLogin()
            const {
                goodsDetail: { is_collect }
            } = this
            const { data, code } = await collectGoods({
                is_collect: is_collect == 0 ? 1 : 0,
                goods_id: this.id
            })
            if (code == 1) {
                if (is_collect == 0) {
                    this.$toast({
                        title: '收藏成功'
                    })
                } else {
                    this.$toast({
                        title: '取消收藏'
                    })
                }
                this.getGoodsDetailFun()
            }
        },
        onChangeGoods(e) {
            console.log(e)
            this.checkedGoods = e.detail
        },
        showSpecFun(type, id) {
            if (!this.isLogin) return toLogin()
            if (this.goodsType == 2 && [2, 3].includes(type)) {
                this.isGroup = 1
                this.foundId = id
            } else {
                this.isGroup = 0
                this.foundId = ''
            }
            this.popupType = type
            this.showSpec = true
        },
        onBuy(e) {
            const id = e.detail.id
            const goodsNum = e.detail.goodsNum
            const insurance = e.insurance

            const { goodsType, team } = this

            let goods = [
                {
                    item_id: id,
                    num: goodsNum
                }
            ]

            const params = {
                goods,
                insurance: insurance
            }
            console.log(params)
            this.showSpec = false
            goodsType == 2 ? (params.teamId = team.team_id) : ''
            this.foundId ? (params.foundId = this.foundId) : ''
            uni.navigateTo({
                url:
                    '/pages/confirm_order/confirm_order?data=' +
                    encodeURIComponent(JSON.stringify(params))
            })
        },
        onConfirm(e) {
            const {
                team: { team_id }
            } = this
            teamCheck({
                team_id,
                found_id: this.foundId
            }).then((res) => {
                if (res.code == 1) {
                    this.onBuy(e)
                }
            })
        },
        async onAddCart(e) {
            let { id, goodsNum } = e.detail

            if (this.goodsType == 2) {
                // 拼团单独购买
                let goods = [
                    {
                        item_id: id,
                        num: goodsNum
                    }
                ]
                uni.navigateTo({
                    url:
                        '/pages/confirm_order/confirm_order?data=' +
                        encodeURIComponent(
                            JSON.stringify({
                                goods
                            })
                        )
                })
                return
            }
            const { code, data, msg } = await addCart({
                item_id: id,
                goods_num: goodsNum
            })
            if (code == 1) {
                this.getCartNum()
                this.$toast({
                    title: msg,
                    icon: 'success'
                })
                this.showSpec = false
            }
        }
    },
    async onShareAppMessage() {
        const { goodsDetail, userInfo } = this
        return {
            title: goodsDetail.name,
            imageUrl: goodsDetail.image,
            path:
                '/pages/goods_details/goods_details?id=' +
                this.id +
                '&invite_code=' +
                userInfo.distribution_code
        }
    },
    computed: {
        ...mapGetters(['cartNum', 'userInfo']),
        btnText() {
            const { goodsType } = this
            switch (goodsType) {
                case 1:
                    return {
                        red: '立即抢购',
                        yellow: ''
                    }
                case 2:
                    return {
                        red: '立即开团',
                        yellow: '单独购买'
                    }
                default:
                    return {
                        red: '立即购买',
                        yellow: '加入购物车'
                    }
            }
        },
        getTeamCountTime() {
            return (time) => time - Date.now() / 1000
        },

        navHeight() {
            return app.globalData.navHeight
        }
    }
}
</script>

<style lang="scss">
.goods-details {
    padding-bottom: calc(120rpx + env(safe-area-inset-bottom));

    .seckill {
        height: 100rpx;
        background: #ffd4d8;

        .price {
            width: 504rpx;
            height: 100%;
            background: url(../../static/images/bg_seckill.png) no-repeat;
            background-size: 100%;
        }

        .down {
            flex: 1;
        }
    }

    .goods-info {
        position: relative;
        margin: 20rpx 20rpx 0 20rpx;
        border-radius: 20rpx;

        .info-header {
            padding: 20rpx 0 0rpx 24rpx;

            .price {
                align-items: baseline;
            }
        }
        .vip-price {
            margin: 0 24rpx;
            background-color: #ffe9ba;
            line-height: 36rpx;
            border-radius: 6rpx;
            overflow: hidden;
            .price-name {
                background-color: #101010;
                padding: 3rpx 12rpx;
                color: #ffd4b7;
                position: relative;
                overflow: hidden;
                &::after {
                    content: '';
                    display: block;
                    width: 20rpx;
                    height: 20rpx;
                    position: absolute;
                    right: -15rpx;
                    background-color: #ffe9ba;
                    border-radius: 50%;
                    top: 50%;
                    transform: translateY(-50%);
                    box-sizing: border-box;
                }
            }
        }
        .name {
            padding: 20rpx 24rpx;
            flex: 1;
        }

        .icon-share {
            width: 134rpx;
            height: 60rpx;
        }
    }

    .discount {
        padding: 24rpx;
        .text {
            width: 100rpx;
            flex: none;
        }

        .con {
            width: 400rpx;
        }

        .coupons-item {
            overflow: hidden;

            & > view {
                position: relative;
                height: 40rpx;
                line-height: 40rpx;
                padding: 0 18rpx;
                border-radius: 6rpx;
                box-sizing: border-box;
                background-color: $-color-ornament;
                color: #fff;
                white-space: nowrap;
                overflow: hidden;

                &::after,
                &::before {
                    content: '';
                    display: block;
                    width: 20rpx;
                    height: 20rpx;
                    position: absolute;
                    left: -14rpx;
                    background-color: #fff;
                    border-radius: 50%;
                    border: 1px solid currentColor;
                    box-sizing: border-box;
                }

                &::after {
                    right: -14rpx;
                    left: auto;
                }
            }
        }
    }

    .details-null {
        padding-top: 140rpx;
        margin-bottom: 100rpx;
    }

    .spec {
        padding: 24rpx 24rpx;

        .text {
            width: 100rpx;
        }
    }

    .evaluation {
        .title {
            height: 100rpx;
            border-bottom: $-solid-border;
            padding: 0 24rpx;
        }

        .con {
            padding: 30rpx 24rpx;
        }

        .user-info .avatar {
            width: 60rpx;
            height: 60rpx;
            border-radius: 50%;
        }
    }

    .details {
        .title {
            line-height: 88rpx;
            text-align: center;
        }

        & > .content {
            padding: 0 20rpx 20rpx;
            overflow: hidden;
            ::v-deep image {
                vertical-align: middle;
            }
            // #ifdef H5
            ::v-deep img {
                vertical-align: middle;
            }
            // #endif
            // #ifdef MP-WEIXIN || APP-PLUS
            ::v-deep ._img {
                display: block;
            }
            // #endif
        }
    }

    .footer {
        height: 100rpx;
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        box-sizing: content-box;
        padding-bottom: env(safe-area-inset-bottom);

        .btn {
            width: 100rpx;
            height: 100rpx;
            position: relative;
            line-height: 1.3;
        }

        .cart-num {
            position: absolute;
            left: 60rpx;
            top: 6rpx;
        }

        .add-cart,
        .right-buy {
            flex: 1;
            text-align: center;
            padding: 16rpx 0;
        }

        .add-cart {
            background-color: rgba(36, 163, 255, 0.1);
        }

        .right-buy {
            background-color: $-color-primary;
        }
    }
}

/* #ifdef MP-ALIPAY */
::v-deep .u-navbar .u-back-wrap .u-icon-wrap {
    background-color: #ffffff !important;
}
::v-deep .u-navbar .u-back-wrap .u-icon-wrap .uicon-nav-back.u-iconfont {
    color: #000000 !important;
}
::v-deep .u-navbar .u-navbar-inner .u-slot-right {
    width: 200rpx;
}
/* #endif */
</style>
